<?php
  class ChargeController extends Controller
  {
      public function filters()
    {
        return array(
            'accessControl', // perform access control for CRUD operations
        );
    }

        public function actions()
    {
        return array(
            // captcha action renders the CAPTCHA image displayed on the contact page
            'captcha'=>array(
                'class'=>'CCaptchaAction',
                'backColor'=>0xFFFFFF,
            ),
            // page action renders "static" pages stored under 'protected/views/site/pages'
            // They can be accessed via: index.php?r=site/page&view=FileName
            'page'=>array(
                'class'=>'CViewAction',
            ),
        );
    }

    public function accessRules()
    {
        return array(

            array('deny', // allow admin user to perform 'admin' and 'delete' actions
                'actions'=>array('index'),
                'expression'    =>    array($this, 'lognined'),
            ),

//            array('deny',  // deny all users
//                'users'=>array('*'),
//            ),
        );
    }

    public function lognined(CWebUser $user, CAccessRule $rule){
//        echo '<pre>', print_r(!empty(Yii::app()->user->id), true), '</pre>';die;
        if (empty(Yii::app()->user->id))
            $this->redirect('/site/login');
        else{
            return false;
        }

    }

        public function actionIndex()
        {
              // Refesh captcha

        $captchaAction = $this->createAction('captcha');
        $captchaAction->getVerifyCode(true);

        $kind=array(
            '92'=>'MOBIFONE',
            '93'=>'VINAPHONE',
            '107'=>'VIETTEL',
            '121'=>'VTC',
        );

        if(isset($_POST['charge'])){
            $mang=$_POST['ChargeCardForm']['kind'];
            $sopin=$_POST['ChargeCardForm']['pin'];
            $seri=$_POST['ChargeCardForm']['seri'];

            if(empty($mang) || empty($sopin) || empty($seri)){
                $this->refresh();
                Yii::app()->user->setFlash('error',Yii::t('label','Tên tài khoản này đã được đăng ký, bạn vui lòng thử tên khác'));
            }

//            Yii::import('ext.BKTransactionAPI');
            include('BKTransactionAPI.php');

            $result=$this->chargeCardSoap($mang, $sopin, $seri);

            if($result['message']=='success')
                Yii::app()->user->setFlash('success',Yii::t('label','Bạn đã nạp thành công thẻ '.$result['mang'].' mệnh giá '.$result['menhgia']));
            else
                Yii::app()->user->setFlash('error',Yii::t('label','Nạp thẻ thất bại, bạn vui lòng kiểm tra lại thông tin vừa nhập.'));

        }

            $model = new ChargeCardForm();
          $this->render('index',array(
              'model'=>$model,
              'kind'=>$kind,
          ));
        }

        function chargeCardSoap($mang, $sopin, $seri)
        {
          $accname = Yii::app()->user->id;
            if($mang==92){
                    $ten = "Mobiphone";
                    $tygia=0.8;
                }
            else if($mang==107){
                    $ten = "Viettel";
                    $tygia=0.8;
                }
            else if($mang==120){
                    $ten = "Gate";
                    $tygia=0.85;
                }
            else if($mang==121){
                    $ten = "VCoin";
                    $tygia=0.85;
                }
            else {
                    $ten ="Vinaphone";
                    $tygia=0.8;
                }

//        $bk = new BKTransactionAPI("http://sandbox.baokim.vn/services/transaction_api/init?wsdl");
//        $secure_pass = 'f2d34bcfe3cd3b12';
//        $transaction_id = time();
//        $info_topup = new TopupToMerchantRequest();
//        $info_topup->api_password = 'nhajben';
//        $info_topup->api_username = 'nhajben';
//        $info_topup->card_id = $mang;
//        $info_topup->merchant_id = '576';



        //$bk = new BKTransactionAPI("https://www.baokim.vn/services/transaction_api/init?wsdl");
        $bk = new BKTransactionAPI("https://www.baokim.vn/the-cao/saleCard/wsdl");
        $secure_pass = '4c5f5d12021c2e2a';
        $transaction_id = time();
        $info_topup = new TopupToMerchantRequest();
        $info_topup->api_password = 'bachkiem489sj28';
        $info_topup->api_username = 'bachkiemkiembach';
        $info_topup->card_id = $mang;
        $info_topup->merchant_id = '7804';

        $info_topup->pin_field = $sopin;
        $info_topup->seri_field = $seri;
        $info_topup->transaction_id = $transaction_id;

        $data_sign_array = (array)$info_topup;
        ksort($data_sign_array);

        $data_sign = md5($secure_pass . implode('', $data_sign_array));
        $info_topup->data_sign = $data_sign;
        $test = new TopupToMerchantResponse();

        $test = $bk->DoTopupToMerchant($info_topup);

            $coinkey = time();
            $sodong = 0;
            if($test->info_card==10000){$sodong = 200000 ;}
            else if($test->info_card==20000){$sodong = 400000;}
            else if($test->info_card==30000){$sodong = 600000;}
            else if($test->info_card==50000){$sodong = 1000000;}
            else if($test->info_card==100000){$sodong = 2000000;}
            else if($test->info_card==200000){$sodong = 4000000;}
            else if($test->info_card==300000){$sodong = 6000000;}
            else if($test->info_card==500000){$sodong = 10000000;}
            $van = $sodong/10000;
            $timezone = +7; //(GMT +7:00)
            $timez= gmdate("d/m/Y H:i:s", time() + 3600*($timezone+date("0")));
            //$sqlsub10=mysql_query("SELECT max(solan) as solan FROM `coincard` where loginName = '".$accname."'");
//            $rowsub10=mysql_fetch_array($sqlsub10);
//            $solan =  $rowsub10['solan'] + 1;

        if($test->error_code==0){
            $coinCardModel = Coincard::model()->findByAttributes(array('loginName'=>$accname));
            $solan = empty($coinCardModel)?0:$coinCardModel->solan;

            $tienthuc= $test->info_card*$tygia;

            /**
            *
            * @var Account
            */
            $account = Account::model()->findByAttributes(array('loginName'=>$accname));
            if(!empty($account)){
                $account->Coin = $account->Coin + $sodong;
                $account->save(false);
            }else die("Tài khoản không tìm thấy");


            $coincard = new Coincard();
            // cái này tù vãi. làm lại trường db
            $coincard->stt = 1;
            $coincard->loginName = $accname;
            $coincard->loaithe = $ten;
            $coincard->menhgia = $test->info_card;
            $coincard->sopin = $sopin;
            $coincard->CoinCardKey = $coinkey;
            $coincard->value = $sodong;
            $coincard->used = 1;
            $coincard->time = $timez;
            $coincard->tienthuc = $tienthuc;
            $coincard->solan = $solan;
            $coincard->save(false);

            return array(
                'message'=>'success',
                'mang'=>$ten,
                'menhgia'=>$test->info_card,
            );

        }

        else {
         return array(
                'message'=>'error',
            );
        }
        }
  }
